package com.txc.pay.alipayLife.utils;

import com.google.gson.Gson;
import com.txc.common.utils.pay.ByteDataBuffer;
import com.txc.openfeign.common.pay.vo.ResBaseVO;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import static com.txc.common.global.constant.NumConstant.ZERO;
import static com.txc.common.global.constant.StrConstant.*;

/**
 * 报文组装
 *
 * @author tao
 * @date 2015-11-11
 */
public class ComposeUtil {
    private static final String SERVCODE = "servCode";

    public static byte[] jsonToBytes(Map<String, Object> head, ResBaseVO resVo) throws Exception {
        String servCode = head.get(SERVCODE).toString().replace(DOUBLE_QUOTES, EMPTY);
        Map<String, Object> resMap = new HashMap<>();
        resMap.put(HEAD, head);
        resMap.put(BODY, resVo);
        Gson juJson = new Gson();
        String message = juJson.toJson(resMap).replace(BACKSLASH, EMPTY);
        ByteDataBuffer bdb = new ByteDataBuffer();
        bdb.setInBigEndian(false);
        bdb.writeInt8((byte) 0x68); // 开始字节
        int len = Integer.parseInt(getLen(message, 4));
        // 用于计算数据域的长度是否大于4字节
        bdb.writeInt32(len); // 报文长度
        bdb.writeString(servCode, 6);// 服务编码
        bdb.writeBytes(message.getBytes()); // 报文frame
        bdb.writeInt8((byte) 0x16); // 结束字节
        return bdb.getBytes();
    }


    /**
     * 计算报文长度，不足四位左补零
     *
     * @param text    报文信息
     * @param needLen 报文长度规定的字符数
     * @return
     */
    public static String getLen(String text, int needLen) {
        if (text != null) {
            int len;
            len = text.getBytes(StandardCharsets.UTF_8).length;
            String lenStr = String.valueOf(len);
            StringBuilder sb = new StringBuilder(lenStr);
            while (sb.length() < needLen) {
                sb.insert(ZERO, ZERO_STR);
            }
            return sb.toString();
        }
        return null;
    }

}
